package com.pengtu.service.test2;

import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author 刘波波
 * @date  2017/4/7
 * @describe handler处理类
 */
@Sharable//注解@Sharable可以让它在channels间共享
public class SimpleServerHandler2 extends ChannelInboundHandlerAdapter {
	@Autowired
	private VehicleInfoManager vehicleInfoManager;
	private Map<ChannelId, Channel> channelMap = new ConcurrentHashMap<ChannelId, Channel>(); 
	/**
	 *@author 刘波波
	 *@date 2017年5月17日
	 *@describe 
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		InetSocketAddress sa = (InetSocketAddress) ctx.channel().remoteAddress();
		System.out.println(sa.getAddress().getHostName()+ ":" + sa.getPort());
		System.out.println(sa.getAddress().getHostAddress()+ ":" + sa.getPort());
		ChannelPipeline cp = ctx.pipeline();
		cp.remove("SimpleServerHandler");
		if(sa.getAddress().getHostAddress().contains("119.138.120.28")){
//			for(Channel ch : channelMap.values()){
//				if(!"com.pengtu.service.netty.SimpleServerHandler".contains(ch.getClass().getName())){
					SimpleServerHandler ssh = new SimpleServerHandler(vehicleInfoManager);
					cp.addLast("SimpleServerHandler",ssh );
//				}
//			}
			ctx.fireChannelRead(msg);
		} else {
			cp.remove("HttpServerCodec");
			cp.remove("HttpObjectAggregator");
			cp.remove("ChunkedWriteHandler");
			cp.remove("TestHandler");
			final int MAX_CONTENT_LENGTH = 65536; 
			cp.addLast("HttpServerCodec",new HttpServerCodec());  
            cp.addLast("HttpObjectAggregator",new HttpObjectAggregator(MAX_CONTENT_LENGTH));  
            cp.addLast("ChunkedWriteHandler",new ChunkedWriteHandler());
            cp.addLast("TestHandler",new TestHandler());
            ctx.fireChannelRead(msg);
		}
	}

	/**
	 *@author 刘波波
	 *@date 2017年5月17日
	 *@describe 
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		super.exceptionCaught(ctx, cause);
	}

	public VehicleInfoManager getVehicleInfoManager() {
		return vehicleInfoManager;
	}

	public void setVehicleInfoManager(VehicleInfoManager vehicleInfoManager) {
		this.vehicleInfoManager = vehicleInfoManager;
	}

	public Map<ChannelId, Channel> getChannelMap() {
		return channelMap;
	}

	public void setChannelMap(Map<ChannelId, Channel> channelMap) {
		this.channelMap = channelMap;
	}


}
